package op3;

import java.util.LinkedList;
import java.util.Queue;

public class FIFO {
    private int frameSize;
    private Queue<Integer> frame; // 页面帧队列
    private int pageFaults; // 缺页次数

    public FIFO(int frameSize) {
        this.frameSize = frameSize;
        this.frame = new LinkedList<>();
        this.pageFaults = 0;
    }

    public void accessPage(int page) {
        if (!frame.contains(page)) {
            pageFaults++;
            if (frame.size() < frameSize) {
                frame.add(page);
            } else {
                // 替换最早进入内存的页面
                frame.poll();
                frame.add(page);
            }
        }
        printFrames();
    }

    public int getPageFaults() {
        return pageFaults;
    }

    private void printFrames() {
        System.out.print("当前占用的页面: ");
        for (int page : frame) {
            System.out.print(page + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int frameSize = 3;
        FIFO fifo = new FIFO(frameSize);
        int[] pageSequence = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};

        for (int page : pageSequence) {
            fifo.accessPage(page);
        }

        System.out.println("缺页次数: " + fifo.getPageFaults());
    }
}